import { defineStore } from 'pinia'
import { store } from '../../index'

// 定义权限配置接口
interface PermissionConfig {
  viewPermission: number // 观看权限：1-公开，2-指定人员
  downloadPermission: number // 下载权限：1-允许，0-禁止
  selectedUsers?: number[] // 选中的用户ID列表
  selectedDepts?: number[] // 选中的部门ID列表
  excludedUsers?: number[] // 排除的用户ID列表
  excludedDepts?: number[] // 排除的部门ID列表
}

// 定义防作弊配置接口
interface AntiCheatingConfig {
  multiplePlay: boolean // 视频倍速播放
  forwardLimit: boolean // 视频快进限制
  popupCheck: boolean // 弹窗防呆校验
  disableDrag: boolean // 禁止视频拖动
  orderStudy: boolean // 顺序学习
  faceRecognition: boolean // 人脸识别
  capture: boolean // 人脸抓拍
}

interface Material {
  id: number
  name: string
  type: string
  catalog: string
  size: number
  duration: number
  createTime: string
}

// 添加基础表单数据接口
interface BasicFormData {
  name: string // 课程名称
  catalog: string // 目录
  teacher: number[] // 讲师ID列表
  tags: number[] // 标签ID列表
  courseType: number | null // 课程类型，允许为 null
  status: number // 状态 1-有效 0-无效
  cover: string // 封面
  validType: number // 有效期类型 1-长期有效 2-按天数 3-固定周期
  validDays?: number // 有效天数
  validPeriod?: string[] // 有效期范围
  teacherIntro: string // 课程介绍
}

interface CentreState {
  selectedMaterials: Material[]
  permissionConfig: PermissionConfig
  antiCheatingConfig: AntiCheatingConfig
  basicFormData: BasicFormData // 添加基础表单数据
  needRefresh: boolean
}

export const useCentreStore = defineStore('centre', {
  state: (): CentreState => ({
    selectedMaterials: [],
    // 初始化权限配置
    permissionConfig: {
      viewPermission: 1,
      downloadPermission: 1,
      selectedUsers: [],
      selectedDepts: [],
      excludedUsers: [],
      excludedDepts: []
    },
    // 初始化防作弊配置
    antiCheatingConfig: {
      multiplePlay: false,
      forwardLimit: false,
      popupCheck: false,
      disableDrag: false,
      orderStudy: false,
      faceRecognition: false,
      capture: false
    } as AntiCheatingConfig,
    basicFormData: {
      name: '',
      teacher: [],
      tags: [],
      courseType: null,
      status: 1,
      cover: '',
      validType: 1,
      validDays: undefined,
      validPeriod: [],
      teacherIntro: ''
    },
    needRefresh: false
  }),

  getters: {
    // 添加新的 getters
    hasSelectedUsers: (state): boolean => {
      return !!(
        state.permissionConfig.selectedUsers?.length || state.permissionConfig.selectedDepts?.length
      )
    },

    hasExcludedUsers: (state): boolean => {
      return !!(
        state.permissionConfig.excludedUsers?.length || state.permissionConfig.excludedDepts?.length
      )
    }
  },

  actions: {
    // 设置选中的课件（支持去重）
    setSelectedMaterials(materials: Material[]) {
      console.log('setSelectedMaterials', JSON.stringify(materials))
      // 使用 Map 来实现去重，以 id 为键
      const uniqueMaterials = new Map()

      // 先保留现有的材料
      this.selectedMaterials.forEach((item) => {
        uniqueMaterials.set(item.id, item)
      })

      // 添加新的材料，如果 id 已存在会自动覆盖
      materials.forEach((item) => {
        uniqueMaterials.set(item.id, item)
      })

      // 将 Map 转换回数组
      this.selectedMaterials = Array.from(uniqueMaterials.values())
    },

    // 清空选中的课件
    clearSelectedMaterials() {
      this.selectedMaterials = []
    },

    // 添加课件
    addMaterial(material: Material) {
      const exists = this.selectedMaterials.some((item) => item.id === material.id)
      if (!exists) {
        this.selectedMaterials.push(material)
      }
    },

    // 移除课件
    removeMaterial(materialId: number) {
      const index = this.selectedMaterials.findIndex((item) => item.id === materialId)
      if (index !== -1) {
        this.selectedMaterials.splice(index, 1)
      }
    },
    // 更新指定用户和部门
    updatePermissionUsers(data: {
      selectedUsers?: number[]
      selectedDepts?: number[]
      excludedUsers?: number[]
      excludedDepts?: number[]
      viewPermission: number // 观看权限：1-公开，2-指定人员
    }) {
      console.log('updatePermissionUsers', JSON.stringify(data))

      if (data.viewPermission !== undefined) {
        this.permissionConfig.viewPermission = data.viewPermission
      }
      if (data.selectedUsers !== undefined) {
        this.permissionConfig.selectedUsers = data.selectedUsers
      }
      if (data.selectedDepts !== undefined) {
        this.permissionConfig.selectedDepts = data.selectedDepts
      }
      if (data.excludedUsers !== undefined) {
        this.permissionConfig.excludedUsers = data.excludedUsers
      }
      if (data.excludedDepts !== undefined) {
        this.permissionConfig.excludedDepts = data.excludedDepts
      }
    },

    // 添加防作弊配置相关方法
    setAntiCheatingConfig(config: Partial<AntiCheatingConfig>) {
      this.antiCheatingConfig = {
        ...this.antiCheatingConfig,
        ...config
      }
    },

    // 更新基础表单数据
    updateBasicFormData(data: Partial<BasicFormData>) {
      this.basicFormData = {
        ...this.basicFormData,
        ...data
      }
    },

    // 获取完整的表单数据
    getFullFormData() {
      return {
        ...this.basicFormData,
        materials: this.selectedMaterials,
        permission: {
          viewPermission: this.permissionConfig.viewPermission,
          downloadPermission: this.permissionConfig.downloadPermission,
          selectedUsers: this.permissionConfig.selectedUsers,
          selectedDepts: this.permissionConfig.selectedDepts,
          excludedUsers: this.permissionConfig.excludedUsers,
          excludedDepts: this.permissionConfig.excludedDepts
        },
        antiCheating: this.antiCheatingConfig
      }
    },

    // 重置所有配置
    resetAllConfig() {
      this.selectedMaterials = []
      this.permissionConfig = {
        viewPermission: 1,
        downloadPermission: 1,
        selectedUsers: [],
        selectedDepts: [],
        excludedUsers: [],
        excludedDepts: []
      }
      this.antiCheatingConfig = {
        multiplePlay: false,
        forwardLimit: false,
        popupCheck: false,
        disableDrag: false,
        orderStudy: false,
        faceRecognition: false,
        capture: false
      }
      this.basicFormData = {
        name: '',
        catalog: '',
        teacher: [],
        tags: [],
        courseType: null,
        status: 1,
        cover: '',
        validType: 1,
        validDays: undefined,
        validPeriod: [],
        teacherIntro: ''
      }
    },

    setNeedRefresh(value: boolean) {
      this.needRefresh = value
    },

    // 添加更新材料的方法
    updateMaterial(updatedMaterial: any) {
      const index = this.selectedMaterials.findIndex((item) => item.id === updatedMaterial.id)
      if (index !== -1) {
        this.selectedMaterials[index] = updatedMaterial
      }
    }
  }
})

// 导出一个可以在组件外使用的函数
export function useCentreStoreWithOut() {
  return useCentreStore(store)
}
